var clock = 0;

function iAlert(msg){
	var msgid = document.getElementById("msg");
	msgid.innerHTML='<p>'+msg+'</p>';
	$("#msg").dialog("open");
}

function convertTime(t){
	var s = Math.floor(t/1000);
	var h = Math.floor(s/3600);
	var m = Math.floor((s%3600)/60);
	s = Math.floor(s-h*3600-m*60);
	return h+" hrs "+m+" mins "+ s +" s ";
}

function updateTimer(){
	
	clock = clock + 1000;
	$(".remaint").each(function(){
		tnow=$(this).attr("t")-clock;
		if(tnow>0){
			$(this).html("Remaining Time: "+convertTime(tnow));
		}else{
			$(this).html("Remaining Time: Timeout");
			document.location="/voteupdate";
		}
	});
}



$(document).ready(function(){
	
	$("#msg").dialog({
		autoOpen: false,
		modal: true,
		buttons:{
			Ok: function(){
				$(this).dialog("close");
			}
		}
	});

	$("#newvote").button();
	$("#pastvotes").button();

	//$("#createvote").dialog("destroy");
	/*
	$("#createvote").dialog({
		autoOpen: false,
		height: 450,
		width: 800,
		title: "New Vote",
		modal: true,
		buttons:{
			"Post":function(){
				if($("#votetopic").attr("value").length==0){
					iAlert("no topic");
				}else{
					$.get('/votepost',{
						topic: $("#votetopic").attr('value'),
						uid: $("#userid").attr("name")
						}, function(data){
							if(data.toString()!=$("#votetopic").attr('value')+" "+$("#userid").attr("name")+" OK"){
								iAlert("Error occur: "+data.toString()+" != "+$("#votetopic").attr('value')+" "+$("#userid").attr("name")+" OK");
							}else{
								document.location="/";
							}
						});
					$(this).dialog("close");
				}
			},
			"Cancel":function(){
				$(this).dialog("close");
			}
		}
	});
	*/
	
	$("#newvote").click(function(e){
		//$("#createvote").dialog("open");
		document.location="/nose.jsp";
	});
	$("#pastvotes").click(function(e){
		document.location="/mouth.jsp";
	});
	
	$(".votebu").css('height','40px').button().click(function(e){
		$.post('/voteforpost',{
			type: $(this).attr("name"),
			vid: $("#userid").attr("name"),
			pid: $(this).attr("id")
		}, function(data){
			if(data.toString()=="Voted!"){
				document.location="/";
			}else {
				iAlert(data.toString());
			}
		});
	});
	setInterval(function(){updateTimer()},1000);
});